package org.summerframework.component.note.manager.impl;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import lombok.extern.slf4j.Slf4j;
import org.summerframework.component.note.NoteResultCode;
import org.summerframework.component.note.PlatformEnum;
import org.summerframework.component.note.config.TencentNoteProperties;
import org.summerframework.component.note.manager.SendNoteService;
import org.summerframework.core.exception.WebException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 石超
 * @version v1.0.0
 */
@Slf4j
public class TencentSendNoteServiceImpl implements SendNoteService {

    private TencentNoteProperties tencentNoteProperties;

    private static final Pattern CONTENT_PATTERN = Pattern.compile("\\$\\{(.*?)}");

    private SmsSingleSender smsSingleSender;

    public TencentSendNoteServiceImpl(TencentNoteProperties tencentNoteProperties) {
        this.tencentNoteProperties = tencentNoteProperties;
        smsSingleSender = new SmsSingleSender(tencentNoteProperties.getAppId(), tencentNoteProperties.getAppKey());
    }

    @Override
    public void sendNote(String account, String nationCode, String signName, String templateCode, String templateContent, Map<String, Object> param) {
        ArrayList<String> params = new ArrayList<>();
        Matcher matcher = CONTENT_PATTERN.matcher(templateContent);

        while (matcher.find()) {
            String key = matcher.group().replaceAll(".*\\{|}.*", "");
            params.add(param.get(key).toString());
        }

        try {
            SmsSingleSenderResult result = smsSingleSender.sendWithParam(nationCode, account,
                    Integer.parseInt(templateCode), params, signName,tencentNoteProperties.getExtend(), tencentNoteProperties.getEtx());

            if (result.result != 0) {
                throw new WebException(NoteResultCode.SEND_NOTE_ERROR);
            }
        } catch (IOException | com.github.qcloudsms.httpclient.HTTPException e) {
            e.printStackTrace();
            throw new WebException(NoteResultCode.SEND_NOTE_ERROR);
        }
    }

    @Override
    public boolean isSupper(Integer platformCode) {
        return PlatformEnum.TENCENT_CLOUD.isType(platformCode);
    }
}
